package com.iring.controller;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.iring.domain.common.User;
import com.iring.vo.common.BooleanResultVO;
import com.iring.vo.common.ResultVO;
import com.iring.vo.sms.SMSCheckVO;
import com.iring.vo.user.CheckUsernameVO;
import com.iring.vo.user.ModPassVO;

/**
 * @author wanggan
 */
@RestController
@RequestMapping("/forget-user")
public class ForgetController extends BaseController {

    /**
     * 检验用户名是否唯一
     *
     * @param checkUsernameVO
     *            检查用户名是否已经存在的vo
     * @return 如果用户名不存在, 则返回true, 存在返回false
     */
    @RequestMapping(value = "/check-username", method = RequestMethod.POST)
    public ResultVO checkUsername(@RequestBody CheckUsernameVO checkUsernameVO) {
        String randomImage = getRandomImage();
        User user = userService.checkUsername(checkUsernameVO,randomImage);
        setTemporaryUser(user.getUsername());
        return new ResultVO(user.getContactPhonenum());
    }

    /**
     * 获取验证码
     *
     * @return 返回成功或者失败
     */
    @RequestMapping(value = "/send-valid-code", method = RequestMethod.POST)
    public BooleanResultVO sendValidCode() {
        // 忘记密码
        checkSessionSendPhoneToken();
        String username = getTemporaryUser();
        Boolean issend = userService.forgetSendCode(username);
        updateSessionSendPhoneTimeStamp();
        return new BooleanResultVO(issend);
    }

    /**
     * 确认验证码
     *
     * @param smsCheckVO
     *            {@link SMSCheckVO}
     * @return 验证验证码是否正确
     */
    @RequestMapping(value = "/verify-valid-code", method = RequestMethod.POST)
    public BooleanResultVO verifyValidCode(@RequestBody SMSCheckVO smsCheckVO) {
        checkAccessToken();
        String username = getTemporaryUser();
        Boolean ischeck = userService.verifyValidCode(smsCheckVO,username);
        removeSessionSendPhoneTimeStamp();
        return new BooleanResultVO(ischeck);
    }

    /**
     * 找回密码 修改密码
     *
     * @param modPassVO
     *            {@link ModPassVO}
     * @return 如果修改成功, 返回用户名, 修改失败进行提示
     */
    @RequestMapping(value = "/modify-password", method = RequestMethod.POST)
    public ResultVO modifyPassword(@RequestBody ModPassVO modPassVO) {
        checkAccessToken();
        String username = getTemporaryUser();
        Boolean isMod = userService.modifyPassword(modPassVO,username);
        if(isMod){
            //如果修改密码成功
            logService.saveLog(username,"modify password",getUserRealIp(),true,"Retrieve the password");
            removeTemporaryUser();
        }
        return new ResultVO(isMod);
    }

}
